/* SQUIB - Scala's Quirky User Interface Builder 
    Copyright (C) 2008 Tim Dalton

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
*/

import scala.collection.mutable.{HashMap}
    
package tfd.scala.squib.scenario.scenegraph {

import java.awt.Component
import java.awt.event.{KeyEvent}
import java.util.EventObject
import com.sun.scenario.scenegraph._
import com.sun.scenario.scenegraph.event._

trait FiresKeyEventsWithNode[T <: {  def addKeyListener(ml:SGKeyListener) }] { self:FiresEventObjectsWithNode with IdableTrait => 
    self.eventHandlers += (keyEvents _).asInstanceOf[(Object, HashMap[String, (EventObject, SGNode) => Unit]) => Unit]

	def keyEvents(comp: T, events:HashMap[String, (EventObject, SGNode) => Unit]):T = {
        val handler = new DelegateKeyEventWithNodeHandler(events);
        if (handler.hasEvents) {
            comp.addKeyListener(handler)
        }
        comp
    }
    
    class DelegateKeyEventWithNodeHandler(events: HashMap[String, (EventObject, SGNode) => Unit]) extends SGKeyListener {
        private val keyPressedDelegate:Option[(KeyEvent, SGNode) => Unit] = events.get("keypressed");
        private val keyReleasedDelegate:Option[(KeyEvent, SGNode) => Unit] = events.get("keyreleased");
        private val keyTypedDelegate:Option[(KeyEvent, SGNode) => Unit] = events.get("keytyped");
        
        lazy val hasEvents = !(keyPressedDelegate.isEmpty 
                          && keyReleasedDelegate.isEmpty
                          && keyTypedDelegate.isEmpty)
                
        override def keyPressed(ke: KeyEvent, node:SGNode) {
            if (!keyPressedDelegate.isEmpty) keyPressedDelegate.get.apply(ke, node)
        }
        
        override def keyReleased(ke: KeyEvent, node:SGNode) {
            if (!keyReleasedDelegate.isEmpty) keyReleasedDelegate.get.apply(ke, node)
        }
        
        override def keyTyped(ke: KeyEvent, node:SGNode) {
            if (!keyTypedDelegate.isEmpty) keyTypedDelegate.get.apply(ke, node)
        }
    }
}
}
